package com.xky.example_student;

import io.jsonwebtoken.*;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.Date;
import java.util.UUID;

/**
 * @author .29.
 * @create 2024-03-15 23:37
 */
@SpringBootTest
public class jwtTest {
    //签名密钥
    String signature = "admin";

    /**
     * 加密生成JWT的测试方法
     */
    @Test
    public void jwt(){
        JwtBuilder builder = Jwts.builder(); //获取JWT生成器
        //使用JWT生成器创建一个JWT
        String jwtToken = builder
                //Header
                .setHeaderParam("typ", "JWT")//类型
                .setHeaderParam("alg", "HS256")//使用的算法
                //Payload
                .claim("name", ".29.")
                .claim("role", "admin")
                .setSubject("admin-test")
                .setExpiration(new Date(System.currentTimeMillis() + 1000*60*60*24))//失效日期：当前时间+24小时
                .setId(UUID.randomUUID().toString())
                //signature
                .signWith(SignatureAlgorithm.HS256, signature)//使用的算法+签名密钥
                //调用compact()方法将三部分拼接起来并用'.'分隔
                .compact();
        System.out.println("生成的JWT：" + jwtToken);
    }

    /**
     * 解密JWT获取信息的测试方法
     */
    @Test
    public void parse(){
        //jwt方法加密出来的密钥
        String jwtToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiLjI5LiIsInJvbGUiOiJhZG1pbiIsInN1YiI6ImFkbWluLXRlc3QiLCJleHAiOjE3MTA2MDUyMjYsImp0aSI6IjFmNTkwNmNjLWQ4MWMtNGQ0MS1hYmJiLWY2M2NkZTg5OTM0ZSJ9.sgkpuvWTyzwDbwmUeKjQt2IuuL2zG0NKrQofdItbBAU";
        JwtParser parser = Jwts.parser();//获取JWT解密工具
        Jws<Claims> claimsJws = parser.setSigningKey(signature).parseClaimsJws(jwtToken); //根据签名密钥对JWT进行解密
        Claims claims = claimsJws.getBody();
        //获取解密出来的载荷内容
        System.out.println("用户名:" + claims.get("name") + "\n"
                        + "规则：" + claims.get("role") + "\n"
                        + "主题:" + claims.getSubject() + "\n"
                        + "ID:" + claims.getId() + "\n"
                        + "失效时间（有效期至）:" + claims.getExpiration()
        );
    }
}

